package cn.itcast.jdbc;

import cn.itcast.util.JDBCUtil;

import java.sql.*;
import java.util.Scanner;

/**
 * 练习:
 * 			需求:
 * 				1.通过键盘录入用户名和密码
 * 				2.判断用户是否登陆成功
 */
public class JDBCDemo9 {

    public static void main(String[] args) {
        //键盘录入,接收用户名和密码
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username = sc.nextLine();
        System.out.println("请输入密码:");
        String password = sc.nextLine();
        //调用方法
        boolean login = new JDBCDemo9().login2(username, password);
        //判读结果,输出不同语句
        if (login){
            System.out.println("登陆成功");
        }else {
            System.out.println("用户名或密码错误");
        }
    }

    /**
     * 登陆方法
     */
    public boolean login(String username, String password){
        if (username == null || password == null){
            return false;
        }
        //连接数据库查看是否登陆成功
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            //获取连接
            conn = JDBCUtil.getConnection();
            //定义SQL
            String sql = "select * from user where username = '"+username+"' and password = '"+password+"'";
            //获取SQL对象
            stmt = conn.createStatement();
            //执行查询
            rs = stmt.executeQuery(sql);
            //判读
            return rs.next();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.Close(rs, stmt, conn);
        }
        return false;
    }

    /**
     * 登陆方法,使用PreparedStatement实现
     * a' or 'a' = 'a
     */
    public boolean login2(String username, String password){
        if (username == null || password == null){
            return false;
        }
        //连接数据库查看是否登陆成功
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            //获取连接
            conn = JDBCUtil.getConnection();
            //定义SQL
            String sql = "select * from user where username = ? and password = ?";
            //获取SQL对象
            pstmt = conn.prepareStatement(sql);
            //给?赋值
            pstmt.setString(1,username);
            pstmt.setString(2,password);
            //执行查询,不需要传参
            rs = pstmt.executeQuery();
            //判读
            return rs.next();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.Close(rs, pstmt, conn);
        }
        return false;
    }

}
